/**
 * @Description:
 * @author GS
 * @date 2013-8-22 下午1:40:33
 */
package com.platform.cdcs.tool;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * @author GS
 */
public class UpdateApk {
    private boolean infoFlag;
    private Context context;
    // --------------------通过解析远程带版本号和Apk下载地址的XML检测是否需要----------------------------------
    private String updateUrl;// json地址获取--http://58.221.238.226/mpManage/version/version.xml

    /**
     * jsonUrl:当前json获取地址
     * 调用xmlCheckAPP()进行更新
     */
    public UpdateApk(Context context, String url) {
        this.context = context;
        this.updateUrl = url;
    }

    /**
     * 通过json获取json，检测更新
     */
    public void checkAPP(boolean flag) {
        this.infoFlag = flag;
        UpdateVersion updateVersion = new UpdateVersion();
        if (updateUrl != null && !("").equals(updateUrl)) {
                updateVersion.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,updateUrl);
                //updateVersion.execute(updateUrl);
        } else {
            // Toast.makeText(context, "更新地址错误，请联系管理员!", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 通过网络解析xml，并返回HashMap对象;
     *
     * @param updateURL
     * @return
     */

    private HashMap<String, String> getXMLHashMap(String updateURL) {
        HashMap<String, String> mHashMap = null;
        try {
            URL url = new URL(updateURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(30 * 1000);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            InputStream inputStream = conn.getInputStream();
            ParseXmlService service = new ParseXmlService();
            mHashMap = service.parseXml(inputStream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mHashMap;
    }

    public class ParseXmlService {
        public HashMap<String, String> parseXml(InputStream inStream) throws Exception {
            HashMap<String, String> hashMap = new HashMap<String, String>();

            // 实例化一个文档构建器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 通过文档构建器工厂获取一个文档构建器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 通过文档通过文档构建器构建一个文档实例
            Document document = builder.parse(inStream);
            // 获取XML文件根节点
            Element root = document.getDocumentElement();
            // 获得所有子节点
            NodeList childNodes = root.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                // 遍历子节点
                Node childNode = (Node) childNodes.item(j);
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element childElement = (Element) childNode;
                    if ("android".equals(childElement.getNodeName())) {
                        childNodes = childElement.getChildNodes();
                        for (int i = 0; i < childNodes.getLength(); i++) {
                            childNode = (Node) childNodes.item(i);
                            if (childNode instanceof Element) {
                                childElement = (Element) childNode;
                                // 版本号

                                // 软件名称
                                if (("name".equals(childElement.getNodeName()))) {
                                    hashMap.put("name", childElement.getFirstChild().getNodeValue());
                                } else if ("number".equals(childElement.getNodeName())) {
                                    hashMap.put("number", childElement.getFirstChild().getNodeValue());
                                }else if("url".equals(childElement.getNodeName())){
                                    hashMap.put("url", childElement.getFirstChild().getNodeValue());
                                }else if("update".equals(childElement.getNodeName())){
                                    hashMap.put("update", childElement.getFirstChild().getNodeValue());
                                }
//                            // 下载地址
//                            else if (("url".equals(childElement.getNodeName()))) {
//                                hashMap.put("url", childElement.getFirstChild().getNodeValue());
//                            } else if ("msg".equals(childElement.getNodeName())) {
//                                hashMap.put("msg", childElement.getFirstChild().getNodeValue());
//                            } else if ("mandatory".equals(childElement.getNodeName())) {
//                                hashMap.put("mandatory", childElement.getFirstChild().getNodeValue());
//                            }
                            }
                        }
                        break;
                    }
                }
            }
            return hashMap;
        }
    }

    /**
     * 更新APK线程
     */
    class UpdateVersion extends AsyncTask<String, Void, HashMap<String, String>> {

        @Override
        protected HashMap<String, String> doInBackground(String... params) {
            return getXMLHashMap(params[0]);
        }

        @Override
        protected void onPostExecute(HashMap<String, String> result) {
            super.onPostExecute(result);
            UpdateManager manager = new UpdateManager(context, result);
            manager.checkUpdate(infoFlag);
        }

    }

}
